import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, ValidationErrors, Validators} from '@angular/forms';
import {BaseService} from '../../../shared/service/base.service';
import {Observable, Observer} from 'rxjs';
import {ApiUrl} from '../../../config/api-url';
import {Consts} from '../../../config/consts';

@Component({
  selector: 'app-device-edit',
  templateUrl: './device-edit.component.html',
  styleUrls: ['./device-edit.component.less']
})
export class DeviceEditComponent implements OnInit {

  @Input()
  isVisible = false;

  @Output()
  emitVisible: EventEmitter<any> = new EventEmitter();
  isOkLoading: any;
  isSpinning: any;

  newDevice: any;
  newDeviceNumber: 1;

  // 模态框表单
  formModel: FormGroup;

  constructor(private fb: FormBuilder, private baseService: BaseService) {
    // this.findResidueNewDeviceToDay();
    this.buildForm();
  }

  ngOnInit(): void {
  }

  // findResidueNewDeviceToDay() {
  //   this.baseService.get(ApiUrl.DeviceUrl + '/findResidueNewDeviceToDay').subscribe(
  //     data => {
  //       if (data.status == 0) {
  //         this.newDevice = data.data;
  //       } else {
  //         this.baseService.layer.messageError('获取可用新设备号数量失败：' + data.msg);
  //       }
  //     }
  //   );
  // }

  buildForm() {
    this.formModel = this.fb.group({
      newDeviceNumber: [null, [Validators.required]],
    });
  }

  handleCancel() {
    this.isOkLoading = false;
    this.isSpinning = false;
    this.isVisible = false;
    this.emitVisible.emit(this.isVisible);
  }

  handleOk() {
    this.isOkLoading = true;
    this.isSpinning = true;

    for (const i in this.formModel.controls) {
      if (this.formModel.controls[i] != this.formModel.controls.user) {
        if (!this.formModel.controls[i].valid) {
          this.isOkLoading = false;
        }
      }
      this.formModel.controls[i].markAsDirty();
      this.formModel.controls[i].updateValueAndValidity();
    }

    let params = {
      newDeviceNumber: this.formModel.value.newDeviceNumber
    };

    this.baseService.post(ApiUrl.DeviceUrl + '/addBatchEstablishNewDevice', params).subscribe((res) => {
      if (res.status == 0) {
        this.isVisible = false;
        this.emitVisible.emit(this.isVisible);
        this.baseService.layer.messageSuccess('生产成功');
        this.formModel.get("newDeviceNumber").setValue('');
      } else {
        this.baseService.layer.messageError('生产失败：' + res.msg);
      }
      this.isOkLoading = false;
      this.isSpinning = false;
      // this.findResidueNewDeviceToDay();
    });
  }
}
